package com.lenovo.agricultureclient.ui.fragment;

import java.util.ArrayList;

import com.lenovo.agricultureclient.R;
import com.lenovo.agricultureclient.bean.ControllerStatus;
import com.lenovo.agricultureclient.request.BaseRequest;
import com.lenovo.agricultureclient.request.ControlRequest;
import com.lenovo.agricultureclient.request.GetControllerStatusRequest;
import com.lenovo.agricultureclient.request.BaseRequest.RequestResult;

import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;
/**
 * 手动控制子窗体
 * @author zongbingwu
 *
 */
public class ControlFragment extends AppBaseFragment
{
	public static final String TAG = "ControlFragment";
	
	private ArrayList<ControllerUiData> mDataList;
	private ControllerUiData mBlowerCtrl;
	private ControllerUiData mRoadlampCtrl;
	private ControllerUiData mWaterCtrl;
	private ControllerUiData mBuzzerCtrl;
	
	//获取控制器状态的请求对象
	private GetControllerStatusRequest mGetControllerStatusRequest;
	//设置控制器状态的请求对象
	private ControlRequest mControlRequest;
	
	private ControllerListAdapter mAdp;
	private GridView mGridView;
	private String mUsername = "";
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		mGetControllerStatusRequest = new GetControllerStatusRequest();
		mGetControllerStatusRequest.setControllerStatus(mApp.getControllerStatus());
		mGetControllerStatusRequest.setOnResponseEventListener(new BaseRequest.OnResponseEventListener() {
			@Override
			public void onResponse(BaseRequest request, RequestResult result) {
				if(mGetControllerStatusRequest.isSuccess())
				{
					//获取控制器状态以后，刷新所有控制器的开关状态
					ControllerStatus status = mGetControllerStatusRequest.getControllerStatus();
					mBlowerCtrl.isOpen = status.getBlower();
					mRoadlampCtrl.isOpen = status.getRoadlamp();
					mWaterCtrl.isOpen = status.getWaterPump();
					mBuzzerCtrl.isOpen = status.getBuzzer();
					mAdp.notifyDataSetChanged();
				}
			}
		});
		
		mControlRequest = new ControlRequest();
		//构建所需要的界面数据
		mDataList = new ArrayList<ControlFragment.ControllerUiData>();
		mBlowerCtrl = new ControllerUiData(getString(R.string.blower), R.drawable.blower_on, R.drawable.blower_off);
		mRoadlampCtrl = new ControllerUiData(getString(R.string.road_lamp), R.drawable.roadlamp_on, R.drawable.roadlamp_off);
		mWaterCtrl = new ControllerUiData(getString(R.string.water_pump), R.drawable.water_pump_on, R.drawable.water_pump_off);
		mBuzzerCtrl = new ControllerUiData(getString(R.string.buzzer), R.drawable.buzzer_on, R.drawable.buzzer_off);
		mDataList.add(mBlowerCtrl);
		mDataList.add(mRoadlampCtrl);
		mDataList.add(mWaterCtrl);
		mDataList.add(mBuzzerCtrl);
		
		mAdp = new ControllerListAdapter(getActivity(), mDataList);
		mUsername = mApp.getUsername();
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		return inflater.inflate(R.layout.control_fragment, container, false);
	}
	
	@Override
	public void onActivityCreated(Bundle savedInstanceState) 
	{
		super.onActivityCreated(savedInstanceState);
		
		mGridView = (GridView)getView().findViewById(R.id.controller_grid_view);
		mGridView.setAdapter(mAdp);
		//设置控制器图标点击事情
		mGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				ControllerUiData data = mDataList.get(position);
				//只要当前是admin账号才有设置权限，否则提示用户缺少控制权限
				if(!mUsername.equals("admin")){
					showAlertDialog(getString(R.string.prompt), getString(R.string.no_authority_exp));
					return;
				}
				data.isOpen = (data.isOpen+1)%2;
				mControlRequest.resetRequest();
				if(data==mBlowerCtrl){
					mControlRequest.setBlower(mBlowerCtrl.isOpen);
				} else if(data==mRoadlampCtrl) {
					mControlRequest.setRoadlamp(mRoadlampCtrl.isOpen);
				} else if(data==mWaterCtrl) {
					mControlRequest.setWaterPump(mWaterCtrl.isOpen);
				} else if(data==mBuzzerCtrl) {
					mControlRequest.setBuzzer(mBuzzerCtrl.isOpen);
				}
				mAdp.notifyDataSetChanged();
				//向服务器端发送设置控制器状态的请求
				startRequest(mControlRequest);
			}
		});
		//向服务器端发送获取控制器状态的请求
		startRequest(mGetControllerStatusRequest);
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
	}

	@Override
	public void onDestroyView() {
		super.onDestroyView();
	}
	//控制器的界面信息类
	class ControllerUiData
	{
		public ControllerUiData(String name, int onIcon, int offIcon)
		{
			this.name = name;
			this.onIcon = onIcon;
			this.offIcon = offIcon;
		}
		public String name = ""; //控制器名称
		public int isOpen = 0; //0表示关闭，1表示打开
		public int onIcon = 0; //控制器打开时的图标ID
		public int offIcon = 0;//控制器关闭时的图标ID
	}
	
	//控制器图标列表适配器
	class ControllerListAdapter extends ArrayAdapter<ControllerUiData>
	{
		private class ViewHolder 
		{
			ImageView imageView; //控制器图标
	        TextView nameTextView;//控制器名称
	        TextView statusTV;	//控制器状态
	        TextView btnTV;//打开或关闭按钮
		}
		private static final String TAG = "<ControllerListAdapter>";
		//控制器的界面信息集合
		private ArrayList<ControllerUiData> mLedDataArray;
		private Context mContext;
		private final LayoutInflater mInflater;
		public ControllerListAdapter(Context context, ArrayList<ControllerUiData> data)
	    {
	    	super(context, 0, data);
	    	mContext = context;
	        mLedDataArray = data;
	        mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
	    }
		public int getCount()
		{
			return mLedDataArray.size();
		}
		public long getItemId(int position) 
	    {
	        return position;
	    }
		@Override
		public ControllerUiData getItem(int position) 
		{
			return mLedDataArray.get(position);
		}
		public View getView(int position, View convertView, ViewGroup parent) 
		{
		    try
	        {
		    	ControllerUiData itemData = (ControllerUiData) getItem(position);
		    	ViewHolder holder = null;
	            if (convertView == null) 
	            {
	            	 convertView = mInflater.inflate(R.layout.controller_item, null);
	            	 holder = new ViewHolder();
	            	 holder.imageView = (ImageView) convertView.findViewById(R.id.controller_icon);
	            	 holder.nameTextView = (TextView)convertView.findViewById(R.id.name_text_view);
	            	 holder.statusTV = (TextView)convertView.findViewById(R.id.status_text_view);
	            	 holder.btnTV = (TextView)convertView.findViewById(R.id.open_text_view);
	            	 convertView.setTag(holder);
	            } 
	            else 
	            {
	                holder = (ViewHolder)convertView.getTag();
	            }
	            if(itemData != null)
	            {
	            	//控制器名称
	            	holder.nameTextView.setText(itemData.name);
	            	String statusStr = mContext.getString(R.string.current_status);
	            	if(itemData.isOpen>0)
	            	{
	            		//设置控制器打开时的图标
	            		holder.imageView.setImageResource(itemData.onIcon);
	            		holder.btnTV.setText(R.string.close);
	            		statusStr += mContext.getString(R.string.open);
	            	}
	            	else
	            	{
	            		//设置控制器关闭时的图标
	            		holder.imageView.setImageResource(itemData.offIcon);
	            		holder.btnTV.setText(R.string.open);
	            		statusStr += mContext.getString(R.string.close);
					}
	            	//控制器状态
	            	holder.statusTV.setText(statusStr);
	            }
	        } 
	        catch (Exception e)
	        {
	            Log.e(TAG, e.toString());
	        }	
		    return convertView;
		}
	}
}
